<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-12-21
 * Time: 下午2:10
 */

namespace api\modules\e_divide\controllers;


use common\components\e_divide\Config;
use common\components\e_divide\EDivide;
use common\components\tools\Api;
use common\components\tools\Model;
use common\components\tools\Tools;
use common\components\wodrow\umeng\MessageClient;
use common\models\credit_app\Message;
use common\models\credit_app\OrderCert;
use common\models\credit_app_tables\Order;
use common\models\credit_old_app\SlEloaninfo;
use common\models\EdiviCommonBackLogs;
use common\models\EdiviCreditOrder;
use common\models\EdiviOrderSendLogs;
use wodrow\yii\rest\ApiException;
use wodrow\yii\rest\Controller;
use function GuzzleHttp\Psr7\str;
use yii\db\Exception;

class NotifyController extends Controller
{
    /**
     * 4.1 统一接口通知
     * @desc post
     * @return string
     * @throws
     */
    public function actionCommonBack()
    {
        $this->onlyDataOut = true;
        $request = \Yii::$app->request;
        if (!$request->isPost){
            return EDivide::notifyBack(11, 11, "必须以post方式请求", "必须以post方式请求");
        }
        $post = \Yii::$app->request->rawBody;
        Tools::log($post, "edivi_commom_back");
        $_p = json_decode($post, true);
        $_opinion = "";
        if (isset($_p['req']['opinion'])){
            $_opinion = $_p['req']['opinion'];
        }
        $_lr_arr = [];
        $_lr_li_arr = [];
        if (isset($_p['req']['loanResult'][0])){
            $_lr_arr = $_p['req']['loanResult'][0];
            if (isset($_p['req']['loanResult'][0]['loanInfo'])){
                $_lr_li_arr = $_p['req']['loanResult'][0]['loanInfo'];
            }
        }
        if (!isset($_p['pub']['orderNo'])){
            return EDivide::notifyBack(12, 12, "没有找到订单号", "没有找到订单号");
        }else{
            $trans_type = $_p['req']['transType'];
            $orderNo = $_p['pub']['orderNo'];
            $edivi_c = EdiviCreditOrder::findOne(['order_no' => $orderNo]);
            if (!$edivi_c){
                return EDivide::notifyBack(13, 13, "没有找到e分期订单", "没有找到e分期订单");
            }
            $order = Order::findOne(['o_id' => $edivi_c->order_no]);
            if (!$order){
                return EDivide::notifyBack(32, 32, "没有找到订单", "没有找到订单");
            }
            if (isset($_p['req']['materials']['mateAdded']['taskId']) && $_p['req']['materials']['mateAdded']['taskId']){
                $edivi_c->bl_task_id = (string)$_p['req']['materials']['mateAdded']['taskId'];
                $edivi_c->bl_task_type = "mateAdded";
            }
            if (isset($_p['req']['materials']['mateCover']['taskId']) && $_p['req']['materials']['mateAdded']['taskId']){
                $edivi_c->bl_task_id = (string)$_p['req']['materials']['mateCover']['taskId'];
                $edivi_c->bl_task_type = "mateCover";
            }
        }
        if ($trans_type == EdiviCommonBackLogs::TRANS_TYPE_4){
            if ($edivi_c->app_uid){
                $title = 'e分期订单授信通过';
                $text = "e分期订单授信通过";
                $data = [
                    'type' => MessageClient::TYPE_CUSTOMIZEDCAST,
                    'alias_type' => 'user',
                    'alias' => [$edivi_c->app_uid],
                    'payload' => [
                        'display_type' => MessageClient::DISPLAY_TYPE_NOTIFICATION,
                        'body' => [
                            'title' => $title,
                            'text' => $text,
                        ],
                    ],
                ];
                $r = \Yii::$app->umeng->send($data);
                $r= json_decode($r, true);
                if (isset($r['ret'])&&$r['ret']=='SUCCESS'){}else{
                    return EDivide::notifyBack(30, 30, "e分期订单授信通过push失败", "e分期订单授信通过push失败");
                }
                if (isset($r['data']['json'])&&$r['data']['json']){
                    $r['data']['json_arr'] = json_decode($r['data']['json']);
                }
            }
            $certs = OrderCert::find()->where(['ct_oid' => $edivi_c->order_no])->all();
            foreach ($certs as $k => $v){
                if ($v->ct_results != "已查询"){
                    $v->ct_results = "未查询";
                }
                $v->ct_electron_result = json_encode(['result' => EdiviCommonBackLogs::getTransTypes()[$trans_type], 'date' => date('Y-m-d H:i:s')], JSON_UNESCAPED_UNICODE);
                $v->save(false);
            }
        }
        if (in_array($trans_type, [EdiviCommonBackLogs::TRANS_TYPE_1, EdiviCommonBackLogs::TRANS_TYPE_9, EdiviCommonBackLogs::TRANS_TYPE_3])){
            if ($order->o_status != "作废"){
                $certs = OrderCert::find()->where(['ct_oid' => $edivi_c->order_no])->all();
                foreach ($certs as $k => $v){
                    $v->ct_results = "已查询";
                    $v->ct_querytime = time();
                    $v->ct_electron_result = json_encode(['result' => EdiviCommonBackLogs::getTransTypes()[$trans_type].";".$_opinion, 'date' => date('Y-m-d H:i:s')], JSON_UNESCAPED_UNICODE);
                    $v->save(false);
                }
                $order->o_status = "征信查询";
                $order->o_search_time = time();
                if (!$order->save(false)){
                    return EDivide::notifyBack(34, 34, Model::getModelError($order), Model::getModelError($order));
                }
            }
        }
        if ($trans_type == EdiviCommonBackLogs::TRANS_TYPE_19){
            $json = <<<JSON
{
    "orderNo": "{$orderNo}"
}
JSON;
            $resp = Api::request('/e_divide/default/credit-confirm', [
                'json' => $json
            ]);
            $resp_arr = json_decode($resp->content, true);
            if ($resp_arr['code']!=200){
                throw new ApiException(201908151527, "请求分期确认异常");
            }
            $certs = $order->certs;
            $users = $edivi_c->ediviCreditOrderUsers;
            $idcards = [];
            foreach ($users as $k => $v) {
                $idcards[] = $v->id_card;
            }
            foreach ($certs as $k =>$v){
                if (in_array($v->ct_code, $idcards)){
                    $v->ct_electron_tag = 1;
                    $v->ct_etron_endtime = time();
                    $v->ct_results = "委托中";
                    $v->save(false);
                }
            }
        }
        $eloaninfo = SlEloaninfo::find()->where(['e_o_number' => $edivi_c->order_no])->one();
        if (!$eloaninfo){
            $eloaninfo = new SlEloaninfo();
            $eloaninfo->e_o_number = $edivi_c->order_no;
            if ($edivi_c->lastCreditSendLog){
                $eloaninfo->e_add_time = $edivi_c->lastCreditSendLog->created_at;
            }
            if ($trans_type == EdiviCommonBackLogs::TRANS_TYPE_3){
                $eloaninfo->e_refuse_time = time();
            }
        }
        $eloaninfo->e_o_number = (string)$eloaninfo->e_o_number;
        $eloaninfo->e_orderNo = (string)$edivi_c->estage_order_no;
        if (!in_array($trans_type, [EdiviCommonBackLogs::TRANS_TYPE_18, EdiviCommonBackLogs::TRANS_TYPE_19])){
            $eloaninfo->e_status = $trans_type;
        }
        if ($_opinion){
            $eloaninfo->e_remark = $_opinion;
        }
        if (!$eloaninfo->save()){
            return EDivide::notifyBack(31, 31, Model::getModelError($eloaninfo), Model::getModelError($eloaninfo));
        }
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $log = new EdiviCommonBackLogs();
            $log->edivi_credit_order_id = $edivi_c->id;
            $log->assurer_no = $_p['assurerNo'];
            $log->bank_type = $_p['bankType'];
            $log->org_code = $_p['orgCode'];
            $log->busi_code = $_p['busiCode'];
            $log->bank_code = $_p['pub']['bankCode'];
            $log->plat_no = $_p['pub']['platNo'];
            $log->trans_type = $trans_type;
            $log->opinion = $_opinion;
            $log->to_api_data = json_encode($_p, JSON_UNESCAPED_UNICODE);
            $log->resp_to_edivi_data = EDivide::generateNotifyBackJson(0, 1, "success", "success");
            $log->created_at = time();
            if (isset($_p['req']['userName']))$log->user_name = $_p['req']['userName'];
            if (isset($_p['req']['idCard']))$log->id_card = $_p['req']['idCard'];
            if (isset($_p['req']['materials']))$log->materials = json_encode($_p['req']['materials'], JSON_UNESCAPED_UNICODE);
            if ($_lr_arr){
                $log->loan_result = json_encode($_lr_arr, JSON_UNESCAPED_UNICODE);
                if (isset($_lr_arr['cardNo']))$log->lr_card_no = $_lr_arr['cardNo'];
                if (isset($_lr_arr['loanDate']))$log->lr_loan_date = $_lr_arr['loanDate'];
                if (isset($_lr_arr['loanStageDate']))$log->lr_loan_stage_date = $_lr_arr['loanStageDate'];
                if (isset($_lr_arr['recstat']))$log->lr_recstat = $_lr_arr['recstat']; // 例：73放款成功 74放款失败 61开户成功 62开户失败
                if ($_lr_li_arr){
                    $log->lr_loan_info = json_encode($_lr_li_arr, JSON_UNESCAPED_UNICODE);
//                    if (isset($_lr_li_arr['loanAmount']))$log->lr_li_loan_amount= $_lr_li_arr['loanAmount'];
//                    if (isset($_lr_li_arr['loanAccount']))$log->lr_li_loan_account = $_lr_li_arr['loanAccount'];
//                    if (isset($_lr_li_arr['loanFlag']))$log->lr_li_loan_flag = $_lr_li_arr['loanFlag']; // 1-车贷,2-附加费
//                    if (isset($_lr_li_arr['firstamt']))$log->lr_li_firstamt = $_lr_li_arr['firstamt'];
//                    if (isset($_lr_li_arr['eachamt']))$log->lr_li_eachamt = $_lr_li_arr['eachamt'];
//                    if (isset($_lr_li_arr['feeamt']))$log->lr_li_feeamt = $_lr_li_arr['feeamt'];
//                    if (isset($_lr_li_arr['eachpfee']))$log->lr_li_eachpfee = $_lr_li_arr['eachpfee'];
//                    if (isset($_lr_li_arr['firstpfee']))$log->lr_li_firstpfee = $_lr_li_arr['firstpfee'];
//                    if (isset($_lr_li_arr['eachdate']))$log->lr_li_eachdate = $_lr_li_arr['eachdate'];
//                    if (isset($_lr_li_arr['nextdate']))$log->lr_li_nextdate = $_lr_li_arr['nextdate'];
//                    if (isset($_lr_li_arr['workdate']))$log->lr_li_workdate = $_lr_li_arr['workdate'];
//                    if (isset($_lr_li_arr['trxspot']))$log->lr_li_trxspot = $_lr_li_arr['trxspot'];
//                    if (isset($_lr_li_arr['resetMsg']))$log->lr_li_trxspot = $_lr_li_arr['resetMsg'];
                }
            }
            if ($log->assurer_no != $edivi_c->assurer_no && $log->bank_type != $edivi_c->bank_type && $log->bank_code != $edivi_c->bank_code && $log->plat_no != $edivi_c->plat_no) {
                Tools::log($edivi_c->bank_code, 'edivi_back_dubug');
                Tools::log($log->bank_code, 'edivi_back_dubug');
                return EDivide::notifyBack(14, 14, "非法请求", "非法请求");
            }
            if (!$log->save()){
                return EDivide::notifyBack(15, 15, Model::getModelError($log), Model::getModelError($log));
            }
            if (!in_array($trans_type, [EdiviCommonBackLogs::TRANS_TYPE_18, EdiviCommonBackLogs::TRANS_TYPE_19])){
                $edivi_c->status = $log->trans_type;
            }
            if ($trans_type == EdiviCommonBackLogs::TRANS_TYPE_2){
                $edivi_c->status = EdiviOrderSendLogs::STATUS_GENERATE_CARD_SEND;
            }
            if (!$edivi_c->save()){
                return EDivide::notifyBack(35, 35, Model::getModelError($edivi_c), Model::getModelError($edivi_c));
            }
            $trans->commit();
        } catch (Exception $e){
            $trans->rollBack();
            return EDivide::notifyBack(20, 20, "异常", "异常");
        }
        if (EdiviCommonBackLogs::TRANS_TYPE_7 == $trans_type){
            $sl_order = $eloaninfo->slOrder;
            if ($sl_order){
                $sl_mp = $sl_order->slMakePledge;
                if ($sl_mp){
                    $sl_mp->mp_credit_no = $log->lr_card_no;
                    $sl_mp->mp_ebank_time = strtotime($log->lr_loan_date);
                    $sl_mp->save(false);
                }
            }
        }
        return EDivide::generateNotifyBackJson(0, 1, "success", "success", "array");
    }

    /**
     * 面签报告推送
     * @desc /get/post
     * @throws
     */
    public function actionFaceValidateReportPush()
    {
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
        Tools::log(\Yii::$app->request->rawBody);
    }
}